package com.powernode.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class OAuthRoute {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 授权的代码方式路由
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator oauthLocator(RouteLocatorBuilder builder){
        return builder.routes()
                .route("oauth-route-id" , r -> r.path(GatewayConstant.OAUTH_PATH)
                .filters(f -> f.modifyResponseBody(String.class,String.class, (exchange,s) -> {
                    //s就是后端服务返回的一个结果
                    JSONObject jsonObject = JSON.parseObject(s);
                    String accessToken = jsonObject.getString(GatewayConstant.ACCESS_TOKEN);
                    if (StringUtils.hasText(accessToken)){
                        //存起来
                        Long expireIn = jsonObject.getLong(GatewayConstant.EXPIRES_IN);
                        //存入redis并设置过期时间
                        redisTemplate.opsForValue().set(GatewayConstant.OAUTH_TOKEN_PREFIX+accessToken,"", Duration.ofSeconds(expireIn));
                    }
                    return Mono.just(s);
                })).uri("lb://auth-server"))
                .build();
    }
}
